﻿using System.IO;
using System.Xml.Linq;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;

namespace Provenance.Write.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpLoadController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly QiniuUtils _qiniuUtils;
        private readonly IPictureInfoRepository _pictureInfoRepository;
        public UpLoadController(IMediator mediator, QiniuUtils qiniuUtils, IPictureInfoRepository pictureInfoRepository)
        {
            _mediator = mediator;
            _qiniuUtils = qiniuUtils;
            _pictureInfoRepository = pictureInfoRepository;
        }
       
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadFile(IFormFile file)
        {
            // 校验文件是否为空
            if (file.Length == 0)
            {
                return BadRequest("未选择文件");
            }
            // 生成文件保存名称
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);

            // 使用 MemoryStream 读取文件数据
            using (var stream = new MemoryStream())
            {
                file.CopyTo(stream);
                byte[] data = stream.ToArray();

                // 调用上传方法
                try
                {
                   var response= _qiniuUtils.UploadFile(data, name);
                    return Ok(response);
                }
                catch (Exception ex)
                {
                    // 捕获上传异常并返回错误信息
                    return StatusCode(500, $"文件上传失败: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<string> DeleteFile(int PictureInfoId)
        {
            var obj =await _pictureInfoRepository.GetAsync(x => x.PictureInfoId == PictureInfoId);
            if(obj==null)
            {
                return "文件不存在";
            }
            var response = _qiniuUtils.DeleteFile(obj.ImageUrl);
            return response;
        }
        





    }
}
